<?php
// +-----------------------+
// | 注释不留名，代码随便用 |
// +-----------------------+


namespace addons\service;


use addons\library\Plugs;
use addons\library\plugs\Module;
use addons\library\plugs\Part;
use library\tools\Http;
use phpDocumentor\Reflection\Type;
use think\Db;
use think\Exception;

class AddonsService
{
    protected static $remote = 'http://api.sanniuben.com';

    protected static $table = 'system_plugs';

    /**
     * 远程资源
     * @return array
     */
    public static function getRemoteResource()
    {
        $result = Http::post(self::$remote . '?s=admin/api.addons/getList');
        $data = json_decode($result, true);
        if (empty($data) || $data['code'] != 1) {
            return [];
        }
        return $data['data'];
    }

    public static function preload($name){
        $result = Http::post(self::$remote . '?s=admin/api.addons/preload', [
            'name' => $name
        ]);
        $response = json_decode($result, true);
        if (empty($response)) {
           throw new Exception('插件不存在或已下架！');
        }
        if($response['code'] != 1){
            throw new Exception($response['msg']);
        }
        return $response['data'];
    }


    public static function install($module, $file, $type, $param = [])
    {
        $addons = Plugs::factory($type, $module);
        $addons->install($file, $param);
    }

    public static function uninstall($module, $type)
    {
        $addons = Plugs::factory($type, $module);
        $addons->uninstall();
    }


    /**
     * 更新插件
     * @auth true
     */
    public static function refresh()
    {
        $plugs = self::getRemoteResource();
        foreach ($plugs as $module) {
            if ($module['status'] == 0) {
                //删除
                Db::name(self::$table)
                    ->where('name', $module['name'])
                    ->delete();
                continue;
            }
            $vo = Db::name(self::$table)
                ->where('name', $module['name'])
                ->find();
            //如果没有则插入
            if (empty($vo)) {
                Db::name(self::$table)->insert([
                    'title' => $module['title'],
                    'type' => $module['type'],
                    'name' => $module['name'],
                    'intro' => $module['intro'],
                    'install_status' => 0
                ]);
            } else {
                //修改
                Db::name(self::$table)
                    ->where('name', $module['name'])
                    ->update([
                        'title' => $module['title'],
                        'type' => $module['type'],
                        'title' => $module['title'],
                        'intro' => $module['intro'],
                    ]);
            }
        }
        return $plugs;
    }


}